import os
import pyautogui
import time
from phone import Phone
from winManger import Process

img_arr = [
    'img/gdkj.jpg',
    'img/kaoqindaka.jpg',
    'img/xiabandaka.jpg',
    'img/dakachenggong.jpg',
    'img/guanbidakaye.jpg',
    'img/xiaoxi.jpg'
]


def init():
    process_name = "scrcpy.exe"
    process = Process()
    is_run = process.isRun(process_name)

    tryTimes = 1
    if is_run:
        print("scrcpy已启动！")
    else:
        print("scrcpy未启动！")

    while is_run is False and tryTimes < 5:
        print("尝试启动第", tryTimes, "次！")
        process.openProcess("D:\\scrcpy\\scrcpyPro.lnk")
        tryTimes = tryTimes + 1
        is_run = process.isRun(process_name)
    if is_run is False:
        print("程序多次启动失败，将退出！")
        exit(1)

    process_info = process.getProcessInfo(process_name)
    print("程序pid为:  ", process_info["pid"])
    hnd = process.get_hwnds_for_pid(process_info["pid"])
    print("程序窗口句柄为:  ", hnd)

    # 置顶并打开窗口
    process.showWindow(hnd)

    left, top, right, bottom = process.getScrcpyProLocation(hnd)
    # 输出坐标信息
    print('窗口位置：[（{}, {}），（{}, {}）]'.format(left, top, right, bottom))

    Phone().makesureScreenOn()

    print("打开钉钉！")
    os.system("adb shell am start com.alibaba.android.rimet/com.alibaba.android.rimet.biz.LaunchHomeActivity")
    # 等待7秒，有可能应用未常驻后台
    print("等待7秒,待应用进入首页！")
    time.sleep(7)


def findPosition(img):
    location = pyautogui.locateCenterOnScreen(img, confidence=0.9)
    if location is not None:
        posX = location.x
        posY = location.y
        print('当前查找按钮:', img, '位置[', str(posX), ',', str(posY), ']')
        return posX, posY
    else:
        return None


def findAndClick(i, sleep=5):
    Phone().makesureScreenOn()

    img = img_arr[i]
    position = findPosition(img)
    if position is not None:
        print("点击", img)
        pyautogui.click(x=position[0], y=position[1], clicks=2, interval=0.01, duration=0.01)

        print("休眠", sleep, "秒！")
        time.sleep(sleep)

        print("检测点击是否成功！")
        position = findPosition(img_arr[i + 1])
        if position is not None:
            print(img, "点击成功！")
            return True
        print(img, "点击失败！")
        return False

    else:
        print("没有这个按钮：", img)
        return False


def start():
    findAndClick(0)
    isOk = findAndClick(1)
    if not isOk:
        print("失败退出！")
        exit(1)

    isOk = findAndClick(2)
    if not isOk:
        print("失败退出！")
        exit(1)

    position = findPosition(img_arr[3])
    if position is not None:
        print("打卡成功！")

    isOk = findAndClick(4)
    if isOk:
        print("关闭打卡页成功！")

    else:
        print("关闭打卡页失败！")
